package com.ktg.mes.pro.service.impl;

import java.util.Arrays;
import java.util.List;
import com.ktg.common.utils.DateUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ktg.common.utils.StringUtils;
import com.ktg.mes.dv.domain.DvMachinery;
import com.ktg.mes.dv.service.IDvMachineryService;
import com.ktg.mes.md.service.IMesScalesOrderItemService;
import com.ktg.mes.pro.domain.ProRouteProcess;
import com.ktg.mes.pro.domain.ProTask;
import com.ktg.mes.pro.service.IProRouteProcessService;
import com.ktg.mes.pro.service.IProTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ktg.mes.pro.mapper.ProTaskDeviceProcessMapper;
import com.ktg.mes.pro.domain.ProTaskDeviceProcess;
import com.ktg.mes.pro.service.IProTaskDeviceProcessService;



/**
 * 创建生产关联（排产任务，生产设备，工序）Service业务层处理
 *
 * @author byteco
 * @date 2022-11-23
 */
@Service
public class ProTaskDeviceProcessServiceImpl extends ServiceImpl<ProTaskDeviceProcessMapper, ProTaskDeviceProcess> implements IProTaskDeviceProcessService
{

    @Autowired
    private IProTaskService proTaskService;

    @Autowired
    private IDvMachineryService dvMachineryService;

    @Autowired
    private IProRouteProcessService proRouteProcessService;

    @Autowired
    private IMesScalesOrderItemService mesScalesOrderItemService;


    /**
     * 查询创建生产关联（排产任务，生产设备，工序）
     *
     * @param entity 创建生产关联（排产任务，生产设备，工序）
     * @param page 分页对象
     * @return 创建生产关联（排产任务，生产设备，工序）
     */
    @Override
    public IPage<ProTaskDeviceProcess> queryPageList(ProTaskDeviceProcess entity, Page<ProTaskDeviceProcess> page) {
        QueryWrapper<ProTaskDeviceProcess> lqw = new QueryWrapper<>(entity);
        lqw.orderByDesc("create_time");
        IPage<ProTaskDeviceProcess> pageList = this.page(page, lqw);
        return pageList;
    }

    /**
     * 查询创建生产关联（排产任务，生产设备，工序）
     *
     * @param entity 创建生产关联（排产任务，生产设备，工序）
     * @return 创建生产关联（排产任务，生产设备，工序）
     */
    @Override
    public List<ProTaskDeviceProcess> queryList(ProTaskDeviceProcess entity) {
        QueryWrapper<ProTaskDeviceProcess> lqw = new QueryWrapper<>(entity);
        lqw.orderByDesc("create_time");
        return this.list(lqw);
    }

    public ProTaskDeviceProcess getInfo(Long id)
    {
        return this.getById(id);
    }


    /**
     * 新增创建生产关联（排产任务，生产设备，工序）
     *
     * @param entity 创建生产关联（排产任务，生产设备，工序）
     * @return 结果
     */
    @Override
    public void insert(ProTaskDeviceProcess entity)
    {

        QueryWrapper<ProTaskDeviceProcess> proTaskDeviceProcessQueryWrapper = new QueryWrapper<>();
        proTaskDeviceProcessQueryWrapper.eq("task_id",entity.getTaskId());
        ProTaskDeviceProcess proTaskDeviceProcess1 = new ProTaskDeviceProcess();
        proTaskDeviceProcess1.setStatus(ProTaskDeviceProcess.statusProduct);
        update(proTaskDeviceProcess1,proTaskDeviceProcessQueryWrapper);

        entity.setCreateTime(DateUtils.getNowDate());
        entity.setStatus(ProTaskDeviceProcess.statusProduct);
        this.save(entity);
    }

    /**
     * 修改创建生产关联（排产任务，生产设备，工序）
     *
     * @param entity 创建生产关联（排产任务，生产设备，工序）
     * @return 结果
     */
    @Override
    public boolean update(ProTaskDeviceProcess entity)
    {
        if (entity.getStatus() != null && ProTaskDeviceProcess.statusProduct.equals(entity.getStatus())){
            QueryWrapper<ProTaskDeviceProcess> proTaskDeviceProcessQueryWrapper = new QueryWrapper<>();
            proTaskDeviceProcessQueryWrapper.eq("task_id",entity.getTaskId());
            ProTaskDeviceProcess proTaskDeviceProcess1 = new ProTaskDeviceProcess();
            proTaskDeviceProcess1.setStatus(ProTaskDeviceProcess.statusEnd);
            update(proTaskDeviceProcess1,proTaskDeviceProcessQueryWrapper);
        }

        entity.setUpdateTime(DateUtils.getNowDate());
        return this.updateById(entity);
    }


    /**
     * 创建或者查找已经存在的数据
     * @param batchNo
     * @param processId
     * @param deviceCode
     * @param type
     * @return
     */
    @Override
    public Object initOrFind(String batchNo,Long processId,String deviceCode,String type){
        ProTaskDeviceProcess proTaskDeviceProcess = new ProTaskDeviceProcess();
        proTaskDeviceProcess.setBatchNo(batchNo);
        proTaskDeviceProcess.setProcessId(Long.valueOf(processId));
        proTaskDeviceProcess.setWorkType(type);
        proTaskDeviceProcess = getOne(new QueryWrapper<ProTaskDeviceProcess>(proTaskDeviceProcess));

        DvMachinery dvMachinery = null;
        if (!StringUtils.isEmpty(deviceCode)){
            dvMachinery = new DvMachinery();
            dvMachinery.setEquipmentCode(deviceCode);
            //获取设备
            dvMachinery = dvMachineryService.getOne(new  QueryWrapper<DvMachinery>(dvMachinery));
            if (dvMachinery == null){
                return "设备不存在";
            }
        }

        if (proTaskDeviceProcess == null){
            ProTask proTask = new ProTask();
            proTask.setBatchNo(batchNo);
            QueryWrapper<ProTask> queryWrapper = new QueryWrapper<>(proTask);
            proTask = proTaskService.getOne(queryWrapper);
            if (proTask == null){
                return "生产批次不存在";
            }

            //获取设备
            ProRouteProcess process = proRouteProcessService.getById(processId);
            if (process == null){
                return "工艺项不存在";
            }

            proTaskDeviceProcess = new ProTaskDeviceProcess();
            proTaskDeviceProcess.setTaskId(String.valueOf(proTask.getTaskId()));
            proTaskDeviceProcess.setTaskName(proTask.getTaskName());
            proTaskDeviceProcess.setBatchNo(proTask.getBatchNo());
            proTaskDeviceProcess.setWorkorderId(proTask.getWorkorderId());
            proTaskDeviceProcess.setScaleId(proTask.getScaleId());

            proTaskDeviceProcess.setProcessId(process.getRecordId());
            proTaskDeviceProcess.setRouteProcessId(process.getRouteId());
            String str = process.getProcessName();
            if (process.getGroupNum() != null){
                str += ":"+process.getGroupNum();
            }
            if (proTaskDeviceProcess.getWorkType() != null){
                str += ":"+proTaskDeviceProcess.getWorkType();
            }
            proTaskDeviceProcess.setProcessName(str);
            proTaskDeviceProcess.setParamJson(process.getParamJson());

            if (dvMachinery != null){
                proTaskDeviceProcess.setDeviceId(dvMachinery.getMachineryId());
                proTaskDeviceProcess.setDeviceName(dvMachinery.getMachineryName());
                proTaskDeviceProcess.setWattHourMeter(dvMachinery.getWattHourMeter());
                proTaskDeviceProcess.setThermometer(dvMachinery.getThermometer());
                proTaskDeviceProcess.setWarmHumid(dvMachinery.getWarmHumid());
            }else {
                proTaskDeviceProcess.setDeviceId(0L);
                proTaskDeviceProcess.setDeviceName("0");
            }

            proTask.setColorCode(process.getColorCode());
            proTaskService.updateById(proTask);

            proTaskDeviceProcess.setWorkType(type);
            insert(proTaskDeviceProcess);
            mesScalesOrderItemService.addCount(proTask.getScaleId(),0.0,proTask.getQuantity().doubleValue(),0.0);
        }else {
            if (dvMachinery != null){
                proTaskDeviceProcess.setDeviceId(dvMachinery.getMachineryId());
                proTaskDeviceProcess.setDeviceName(dvMachinery.getMachineryName());
                proTaskDeviceProcess.setWattHourMeter(dvMachinery.getWattHourMeter());
                proTaskDeviceProcess.setThermometer(dvMachinery.getThermometer());
                proTaskDeviceProcess.setWarmHumid(dvMachinery.getWarmHumid());
            }
            proTaskDeviceProcess.setStatus(ProTaskDeviceProcess.statusProduct);
            update(proTaskDeviceProcess);
        }
        return proTaskDeviceProcess;
    }


    /**
     * 批量删除创建生产关联（排产任务，生产设备，工序）
     *
     * @param recorids 需要删除的创建生产关联（排产任务，生产设备，工序）主键
     * @return 结果
     */
    @Override
    public boolean delete(Long[] recorids)
    {

        return this.removeByIds(Arrays.asList(recorids));
    }

    /**
     * 删除创建生产关联（排产任务，生产设备，工序）信息
     *
     * @param recorid 创建生产关联（排产任务，生产设备，工序）主键
     * @return 结果
     */
    @Override
    public boolean delete(Long recorid)
    {
        return this.removeById(recorid);
    }


}
